<template>
  <div class="admin-info-container">
    <el-main style="background-color: #fff; border-radius: 20px; padding: 20px">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/manage' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>账户设置</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 表单内容 -->
      <el-form
        :model="userForm"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="用户ID">
          <el-input v-model="userForm.userId" disabled />
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>

        <el-form-item label="创建时间">
          <el-input v-model="userForm.createdAt" disabled />
        </el-form-item>

        <el-form-item label="更新时间">
          <el-input v-model="userForm.updatedAt" disabled />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="text" @click="dialogVisible = true"
            >修改密码</el-button
          >
        </el-form-item>
      </el-form>
    </el-main>
    <el-dialog
      title="修改密码"
      :visible.sync="dialogVisible"
      class="address-dialog"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        class="form"
        :model="dialogForm"
        :rules="dialogRules"
        ref="dialogFormRef"
        label-width="auto"
      >
        <el-form-item prop="oldPassword" label="旧密码">
          <el-input
            type="password"
            v-model="dialogForm.oldPassword"
            placeholder="请输入旧密码"
            show-password
          />
        </el-form-item>
        <el-form-item prop="newPassword" label="新密码">
          <el-input
            type="password"
            v-model="dialogForm.newPassword"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input
            type="password"
            v-model="dialogForm.confirmPassword"
            placeholder="请确认密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="editPassword">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    let password = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else if (value.length < 6 || value.length > 20) {
        callback(new Error("密码的长度必须为6~20位"));
      } else {
        callback();
      }
    };
    let confirmPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请确认密码"));
      } else if (value !== this.dialogForm.newPassword) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };
    return {
      size: "small",
      userForm: {
        userId: "",
        username: "",
        email: "",
        phone: "",
        createdAt: "",
        updatedAt: "",
      },
      userFormCopy: {
        userId: "",
        username: "",
        email: "",
        phone: "",
        createdAt: "",
        updatedAt: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "邮箱格式不正确", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
      },
      dialogVisible: false,
      dialogForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      dialogRules: {
        oldPassword: [
          { required: true, message: "请输入旧密码", trigger: "blur" },
        ],
        newPassword: [{ validator: password, trigger: "blur", required: true }],
        confirmPassword: [
          { validator: confirmPassword, trigger: "blur", required: true },
        ],
      },
    };
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      this.$axios.get(`/admin/user/get/${this.$store.state.user.userId}`).then(
        (res) => {
          if (res && res.data.code === 200) {
            this.userForm = res.data.data;
            this.userFormCopy = JSON.parse(JSON.stringify(res.data.data));
          } else {
            this.$message.error(res.data.data || "获取用户信息失败");
          }
        },
        (err) => {
          this.$message.error(err || "获取用户信息失败");
        }
      );
    },
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$axios
            .put("/admin/user/update", {
              email: this.userForm.email,
              phone: this.userForm.phone,
              username: this.userForm.username,
            })
            .then(
              (res) => {
                if (res && res.data.code === 200) {
                  this.userFormCopy = JSON.parse(JSON.stringify(this.userForm));
                  this.$message.success("用户信息已更新");
                  this.$store.commit("updateUserInfo", this.userForm);
                  this.load();
                } else {
                  this.$message.error(res.data.data || "用户信息更新失败");
                }
              },
              (err) => {
                this.$message.error(err || "获取用户信息失败");
              }
            );
        }
      });
    },
    resetForm() {
      this.userForm = JSON.parse(JSON.stringify(this.userFormCopy));
    },
    handleClose() {
      this.dialogVisible = false;
      this.$set(this.dialogForm, "oldPassword", "");
      this.$set(this.dialogForm, "newPassword", "");
      this.$set(this.dialogForm, "confirmPassword", "");
      this.$refs.dialogFormRef.clearValidate();
    },
    logout() {
      this.$store.commit("logout");
      this.$message.success("修改密码成功，请重新登录！");
      this.$router.replace("/login");
    },
    editPassword() {
      this.$refs.dialogFormRef.validate((valid) => {
        if (valid) {
          this.$axios
            .post("/user/profile/changePwd", {
              oldPassword: this.dialogForm.oldPassword,
              newPassword: this.dialogForm.newPassword,
              confirmPassword: this.dialogForm.confirmPassword,
            })
            .then((response) => {
              if (response.data.code === 200) {
                this.dialogVisible = false;
                this.logout();
              } else {
                this.$message.error(response.data.message);
              }
            });
        }
      });
    },
  },
};
</script>

<style lang="scss">
.admin-info-container {
  min-height: 800px;
  padding: 20px;
  border-radius: 20px;
  background-color: #fff;

  .user-form {
    margin: 0 auto;
    max-width: 600px;
    margin-top: 30px;
  }
}
</style>
